/**
 * Created by huangxiaolu on 2014/4/10.
 */
var http = require('http');
var port = process.env.port || 8888;

var url = require('url');
http.createServer(function(req,res){
    console.log('message incoming');
    var path = url.parse(req.url).pathname;
    console.log('request for %s',path);
    var options = {
        hostname: 'localhost',
        port: 3001,
        path: path,
        method:req.method,
        headers: req.headers
    };
   var req1 = http.request(options,function(res1) {
        console.log('response forwarding');
        console.log('res1 type: %s', res1);
        //res.pipe(res1);//.wrap(res1);
       console.log('response code:%s;headers: %s',res1.statusCode,JSON.stringify(res1.headers));
       res.writeHead(res1.statusCode,res1.headers);
       res1.on('data',function(chunk){
           var done = res.write(chunk);
           console.log('BODY: %s.done? %s' , chunk,done);
           if(done) res.end();
       })
        //res1.end();
    });
        req1.end();
    }
).listen(port,function(){
        console.log('proxy listening on port 8888')});
